package com.edu.whty.common.tools;

import java.util.concurrent.*;

public class ThreadPool {
	 // 定义一个私有构造方法
    private ThreadPool() { 
     
    }   
	private static volatile ExecutorService executorService;

	public static ExecutorService getIstance() {
		// 对象实例化时与否判断（不使用同步代码块，instance不等于null时，直接返回对象，提高运行效率）
        if (executorService == null) {
            //同步代码块（对象未初始化时，使用同步代码块，保证多线程访问时对象在第一次创建后，不再重复被创建）
            synchronized (ThreadPool.class) {
                //未初始化，则初始instance变量
                if (executorService == null) {
                	executorService = createExecutor();
                }   
            }   
        }   
		return executorService;
	}
	 
	private static ExecutorService createExecutor() {
		LinkedBlockingDeque<Runnable> queue = new LinkedBlockingDeque<Runnable>(
				1000);
		ThreadPoolExecutor executor = new ThreadPoolExecutor(10,
				30, 10, TimeUnit.MILLISECONDS, queue, new ThreadFactory() {
					@Override
					public Thread newThread(Runnable runnable) {
						Thread thread = new Thread(runnable, "dispatch-thread");
						thread.setDaemon(true);
						return thread;
					}
				});
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy() {
			@Override
			public void rejectedExecution(Runnable runnable,
					ThreadPoolExecutor threadPoolExecutor) {
				System.out.println("reject");
				super.rejectedExecution(runnable, threadPoolExecutor);
			}
		});
		return executor;
	}

}
